import dayjs from "dayjs";
import catalogueForm from "../catalogueForm.vue";
import productForm from "../productForm.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  pro_cate_list,
  pro_cate_add,
  pro_cate_save,
  pro_cate_del,
  pro_list,
  pro_add,
  pro_save,
  pro_del
} from "@/api/product";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { CatalogueFormItemProps, ProductFormItemProps } from "./types";
import { deviceDetection } from "@pureadmin/utils";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_proCate_control: false, // 分类增删改
    is_proItem_control: false, // 产品增删改
  })

  /** 目录相关 start */
  const cateLoading = ref(false);
  const catalogueList = ref([]);

  // 获取产品分类
  async function getProCateListFn() {
    cateLoading.value = true;
    const result = await pro_cate_list({
      page: 1,
      pagesize: 999
    });
    if (result.data.length) {
      let cateList = result.data;
      catalogueList.value = cateList;
      form.cateId = cateList[0].id;
      onSearch();
    } else {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    }
    setTimeout(() => {
      cateLoading.value = false;
    }, 500);
  }

  // 切换产品分类
  function changeCateId(item) {
    form.cateId = item.id;
    onSearch();
  }

  // 对分类数据操作
  function handleCatalogueCommand(row, e) {
    if (e == "edit") openCatalogueDialog("编辑", row);
    else if (e == "delete") catalogueDetele(row);
  }

  // 删除目录
  function catalogueDetele(row) {
    ElMessageBox.confirm("确定删除该目录？", "重要提示", {
      type: "warning"
    }).then(() => {
      pro_cate_del({
        id: row.id
      }).then(res => {
        if (res.code == 1000) {
          message("删除成功", { type: "success" });
          getProCateListFn(); // 刷新目录数据
        } else {
          message(res.msg, { type: "error" });
        }
      });
    }).catch(() => {});
  }

  // 表单
  const catalogueFormRef = ref();
  // 新增、编辑
  function openCatalogueDialog(title = "新增", row?: CatalogueFormItemProps) {
    addDialog({
      title: `${title}目录`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? ""
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(catalogueForm, { ref: catalogueFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = catalogueFormRef.value.getRef();
        const curData = options.props.formInline as CatalogueFormItemProps;
        function chores() {
          message(`您${title}了目录名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          getProCateListFn(); // 刷新目录表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            let curForm = JSON.parse(JSON.stringify(curData));
            if (!curForm.id) delete curForm.id;
            // 表单规则校验通过
            if (title === "新增") {
              pro_cate_add(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            } else {
              pro_cate_save(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  /** 列表相关 start */
  const form = reactive({
    cateId: null,
    page: 1,
    pagesize: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "id",
      prop: "id",
      minWidth: 130
    },
    {
      label: "产品名",
      prop: "name",
      minWidth: 200
    },
    // {
    //   label: "产品简介",
    //   prop: "content",
    //   minWidth: 500
    // },
    {
      label: "类型",
      prop: "cateId",
      minWidth: 180,
      formatter: ({ cateId }) => catalogueList.value.filter(item => item.id == cateId)[0].name
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 180,
      formatter: ({ created_at }) => dayjs.unix(created_at).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.pagesize = val
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  // 对数据操作
  function handleCommand(row, e) {
    if (e == "edit") openProductDialog("编辑", row);
    else if (e == "delete") handleDelete(row);
  }

  // 删除操作
  function handleDelete(row) {
    ElMessageBox.confirm("确定删除该产品", "重要提示", {
      type: "warning"
    }).then(() => {
      pro_del({
        id: row.id
      }).then(res => {
        if (res.code == 1000) {
          message("删除成功", { type: "success" });
          onSearch(); // 刷新表格数据
        } else {
          message(res.msg, { type: "error" });
        }
      });
    }).catch(() => {});
  }

  // 表单
  const productFormRef = ref();
  // 新增、编辑
  function openProductDialog(title = "新增", row?: ProductFormItemProps) {
    addDialog({
      title: `${title}产品`,
      props: {
        formInline: {
          catalogueOption: catalogueList.value,
          id: row?.id ?? "",
          name: row?.name ?? "",
          cateId: row?.cateId ?? ""
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(productForm, { ref: productFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = productFormRef.value.getRef();
        const curData = options.props.formInline as ProductFormItemProps;
        function chores() {
          message(`您${title}了产品名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            let curForm = JSON.parse(JSON.stringify(curData));
            delete curForm.catalogueOption;
            if (!curForm.id) delete curForm.id;
            // 表单规则校验通过
            if (title === "新增") {
              pro_add(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            } else {
              pro_save(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const result = await pro_list(toRaw(form));

    dataList.value = result.data;
    pagination.total = result.count;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  onMounted(() => {
    getProCateListFn();

        /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/productManagement/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/productManagement/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);
      // proCate_control
      if (homeDataObj.proCate_control) permissions.is_proCate_control = true
      // proItem_control
      if (homeDataObj.proItem_control) permissions.is_proItem_control = true
    }
  });

  return {
    permissions,

    cateLoading,
    catalogueList,
    changeCateId,

    form,
    loading,
    columns,
    dataList,
    pagination,
    deviceDetection,

    handleCatalogueCommand,
    openCatalogueDialog,

    onSearch,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleCommand,
    openProductDialog
  };
}
